package com.dorso.service;

import com.dorso.dao.SupplierRepository;
import com.dorso.entity.Product;
import com.dorso.entity.Supplier;
import com.dorso.exception.ProductAdminException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class SupplierService {
    @Autowired
    SupplierRepository supplierRepository;

    //添加供应商
    public Supplier addSupplier(Supplier supplier) throws ProductAdminException {
        if (supplier.getId() != null) {
            if (supplierRepository.findById(supplier.getId()).isPresent()) {
                throw new ProductAdminException("添加供应商失败：供应商已经存在");
            }
        }
        return supplierRepository.save(supplier);
    }

    //根据id查找
    public Supplier getSupplier(long id){
        return supplierRepository.findById(id).get();
    }
    //更新供应商信息
    public Supplier updateSupplier(long id, Supplier supplier) throws ProductAdminException {
        if (!supplierRepository.findById(id).isPresent()) {
            throw new ProductAdminException("修改供应商失败：供应商"+id+"不存在");
        }
        return supplierRepository.saveAndFlush(supplier);
    }
    //删除供应商
    public void deleteSupplier(long id) {
        supplierRepository.deleteById(id);
    }

}
